package com.itheima.service.impl.system;

import com.github.pagehelper.PageHelper;
import com.itheima.domain.system.Permission;
import com.itheima.domain.system.Role;
import com.itheima.mapper.system.RoleMapper;
import com.itheima.service.system.RoleService;
import com.itheima.utils.IdUtil;
import com.itheima.utils.MapperUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class RoleServiceImpl implements RoleService {
    @Override
    public List<Role> list(int pageN, int pageS) {
        RoleMapper mapper = MapperUtil.getMapper(RoleMapper.class);
        PageHelper.startPage(pageN, pageS);
        return mapper.findAll();
    }

    @Override
    public Permission findById(String id) {
        RoleMapper mapper = MapperUtil.getMapper(RoleMapper.class);
        //return mapper.findById();
        return null;
    }

    @Override
    public void save(Role role) {
        RoleMapper mapper = MapperUtil.getMapper(RoleMapper.class);
        role.setId(IdUtil.getId());
        mapper.save(role);
    }

    @Override
    public void delete(String id) {
        SqlSession session = MapperUtil.getSession();
        RoleMapper mapper = session.getMapper(RoleMapper.class);
        mapper.deletePermRole(id);
        session.commit();
        mapper.deleteUserRole(id);
        session.commit();
        mapper.deleteById(id);
        session.commit();
        session.commit();
        session.close();
    }

    @Override
    public Role findRole(String rid) {
        RoleMapper mapper = MapperUtil.getMapper(RoleMapper.class);
        return mapper.findRoleByRid(rid);
    }

    @Override
    public List<String> findPermById(String id) {
        RoleMapper mapper = MapperUtil.getMapper(RoleMapper.class);
        return mapper.findPermById(id);
    }

    @Override
    public void savePerm(String rid, String[] ids) {
        SqlSession session = MapperUtil.getSession();
        RoleMapper mapper = session.getMapper(RoleMapper.class);
        mapper.deletePermRole(rid);
        session.commit();
        for (String id : ids) {
            mapper.saveRolePerm(rid,id);
            session.commit();
        }
        session.close();
    }

    @Override
    public List<Role> findAll() {
        RoleMapper mapper = MapperUtil.getMapper(RoleMapper.class);
        return mapper.findAll();
    }

    @Override
    public List<Role> selectLike(String msg, int pageN, int pageS) {
        RoleMapper mapper = MapperUtil.getMapper(RoleMapper.class);
        PageHelper.startPage(pageN, pageS);
        String roleName = "%"+msg+"%";
        return mapper.selectLike(roleName);
    }

}
